package 笔试.慧金科技;

import java.util.Arrays;

//在排序数组中查找元素的第一个和最后一个位置，要求时间复杂度为O(logn)
public class LeetCode34 {
    public static int[] searchRange(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int first = -1;
        int last = -1;
        if (nums.length == 0) {
            return new int[]{first, last};
        }
        //找第一个等于target的位置
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                first = mid;
                //由于这里是找第一个出现的，我们就往当前的左边继续找，更新右边界
                right = mid - 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        //找第二个等于target的位置
        left = 0;
        right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                last = mid;
                //由于这里是找最后一个出现target的位置，所以就往右边找，更新左边界
                left = mid + 1; //关键
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return new int[]{first, last};
    }

    public static void main(String[] args) {
        int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 8;
        int[] ints = searchRange(nums, target);
        System.out.println(Arrays.toString(ints));
    }
}
